package com.atung.merchant.config.security;

import com.atung.merchant.dto.AuthUserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangbo
 * @since 2022/10/17 14:32
 */
@Component
public class JwtTokenUtil implements Serializable {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private String secret = "wb1234567890";
    private Long expiration = 300000000L;
    private String header = "wb_header";

    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();

        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    public String generateToken(AuthUserEntity userDetails, HttpServletRequest httpServletRequest) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put("id", userDetails.getId());
        claims.put("created", new Date());
        claims.put("ipConfig", WebIpUtil.getIpAddress(httpServletRequest));
        return generateToken(claims);

    }

    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.get("id").toString();

        } catch (Exception e) {
            username = null;

        }
        return username;

    }

    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    public Boolean isTokenIp(String token, String ip) {
        try {
            Claims claims = getClaimsFromToken(token);
            String ipConfig = claims.get("ipConfig").toString();
            if (ipConfig.equals(ip)) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put("created", new Date());
            refreshedToken = generateToken(claims);

        } catch (Exception e) {
            refreshedToken = null;

        }
        return refreshedToken;
    }

    public Boolean validateToken(String token, AuthUserEntity user) {
        String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));

    }

}